//
//  LHStatusListViewModel.swift
//  SinaWeibo
//
//  Created by 美食家 on 17/4/3.
//  Copyright © 2017年 不孤独的美食家. All rights reserved.
//

import Foundation
///sh上拉刷新尝试最大次数
private let maxpulluptryTime = 3

///微博数据列表视图模型
class LHStatusListViewModel {
    
    lazy var statusList = [LHStatusModel]()
    ///上拉刷新错误次数
    private var errorTryTime = 0
    
    func loadStatusLit(pullup:Bool,completion:@escaping (_ IsSuccess:Bool,_ shouldRefresh:Bool)->()) -> Void {
        
        if pullup && errorTryTime>maxpulluptryTime{
            completion(true,false)
            return
        }
        
        let since_id = pullup ?  0 : (statusList.first?.id ?? 0)
        let max_id   = !pullup ? 0 : (statusList.last?.id ?? 0)
        
        LHNetWorkManager.shared.statusList(since_id: since_id,max_id: max_id) { (json, IsSuccess) in
            
           guard let array = NSArray.yy_modelArray(with:LHStatusModel.self,json:json ?? []) as? [LHStatusModel] else{
            completion(IsSuccess,false)
                      return
            }
            print("获取到\(array.count)-----数据\(json)")
            if pullup{
                //上拉刷新，将数据插入到末尾
                self.statusList+=array
            }else{
                //下拉刷新，将数据拼接到最前面
                self.statusList=array+self.statusList
            }
            
            if pullup && array.count==0{
                 self.errorTryTime+=1
                completion(IsSuccess,false)
            }else{
                completion(IsSuccess,true)
            }
            
            
        }

    }
}
